#include "DummyWeapon.h"

#include "DummyBullet.h"

using namespace mega;


DummyWeapon::DummyWeapon()
	: m_bulletSize(10.f)
	, m_acceleration(1.f)
	, m_shape(10.f)
{
	m_shape.setPosition(this->getPosition());
	m_shape.setFillColor(sf::Color(255, 150, 100));
}


DummyWeapon::DummyWeapon(const DummyWeapon & _rhs)
	: m_shape(_rhs.m_shape)
	, m_acceleration(_rhs.m_acceleration)
	, m_bulletSize(_rhs.m_bulletSize)
{
	for (auto iter = std::begin(_rhs.m_bullets); iter != std::end(_rhs.m_bullets); ++iter)
		m_bullets.push_back(new DummyBullet((*iter)->getPosition(), m_bulletSize));
}


DummyWeapon & DummyWeapon::operator=(const DummyWeapon & _rhs)
{
	m_shape        = _rhs.m_shape;
	m_acceleration = _rhs.m_acceleration;
	m_bulletSize   = _rhs.m_bulletSize;

	// delete old bullets
	for (auto iter = std::begin(m_bullets); iter != std::end(m_bullets); ++iter)
		delete *iter;
	m_bullets.clear();

	// add new ones
	for (auto iter = std::begin(_rhs.m_bullets); iter != std::end(_rhs.m_bullets); ++iter)
		m_bullets.push_back(new DummyBullet((*iter)->getPosition(), m_bulletSize));

	return *this;
}


DummyWeapon::~DummyWeapon()
{
	for (auto iter = std::begin(m_bullets); iter != std::end(m_bullets); ++iter)
		delete *iter;
}


void DummyWeapon::move(const Position & _offset)
{
	GameObject::move(_offset);

	m_shape.move(_offset);
}


void DummyWeapon::createBullet(const Position & _direction)
{
	Position d = _direction - this->getPosition();

	DummyBullet * b = new DummyBullet(this->getPosition(), m_bulletSize);

	// Pythagoras was here
	float c = std::sqrt(d.x*d.x + d.y*d.y);

	b->setVelocity(d.x/c * m_acceleration, d.y/c * m_acceleration);

	m_bullets.push_back(b);
}


void DummyWeapon::render(RenderTarget & _target)
{
	updateState();

	_target.draw(m_shape);

	for (auto iter = std::begin(m_bullets); iter != std::end(m_bullets); ++iter)
		(*iter)->render(_target);
}


void DummyWeapon::updateState()
{
	for (auto iter = std::begin(m_bullets); iter != std::end(m_bullets); ++iter)
		(*iter)->updateState();
}
